<?php

// +----------------------------------------------------------------------
// |用户服务层
// +----------------------------------------------------------------------

namespace app\common\system;

use app\admin\controller\User;
use app\common\Model\UserModel;
use think\facade\Validate;
use think\facade\Db;
use think\facade\Session;
use app\common\service\utils\Utils;
use  app\common\system\UserLogService;
use app\common\system\SettingService;
use app\admin\Model\AuthGroupsModel;

/**
 * 登录退出
 */
class UserService
{
/**
     * 用户列表
     * @param array $param 用户列表  
     * @return array|Exception
     */
    public static function list($param)
    {      
        $UserModel = new UserModel(); 
        $AuthGroups = new AuthGroupsModel();
        $pk = $UserModel->getPk();  
        $params= $param['params'];
        $field = $pk . ',nickname,status,registertime,storgeid';   
        $where =$map = [];  
        if($params['userid']){
            $map[] = ['uid ','=',$params['userid']];
        }   
        if($params['auths']){
            $map[] = ['group_id','=',$params['auths']];
        }       
        
        //如果查询条件有传入用户跟权限分组，则查询的条件为用户跟权限分组 
        
        $authgroups_list = $AuthGroups->alias('a')->join('auth_group_access b ','a.id=b.group_id')->where($map)->fieldRaw('group_concat(title) as title,uid')->group('uid')->select()->toArray();
        if($authgroups_list){
            $where[] = ['id','in',array_column($authgroups_list,'uid')];
        }
        $authgroupslist = array_column($authgroups_list,null,'uid');   
        $where['is_delete']=1;
        if($params['status']==2){
            $where[] = ['status', '=', 0];
        }else  if($params['status']==1){
            $where[] = ['status', '=', 1];
        }   
        if($params['storageid']){
            $where[] = ['storgeid','=',$params['storageid']];
        }
        $user= $UserModel->field($field)->where($where)->order('id asc,status asc')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray();  
       
        if($user['data']){
                foreach ($user['data'] as $k => $v) {   
                    $user['data'][$k]['auth_name']= isset($authgroupslist[$v['id']])? $authgroupslist[$v['id']]['title'] : '无';            
                }
        }
        $data['list']=$user['data'];
        $data['total']=$user['total'];
        return $data; 
    }
    


    /**
     * 用户登录
     *
     * @param array $param 登录信息
     * @Apidoc\Returned("adminToken", type="string", require=true, desc="adminToken")
     * @return array|Exception
     */
    public static function login($param)
    {      
        $model = new UserModel();
        $pk = $model->getPk();       
        $field = $pk . ',password,status,username,is_delete,nickname';   
        $where[] = ['username', '=', $param['params']['username']]; 
            
        $user = $model->field($field)->where($where)->find();      
      
        if (empty($user)) {
            error('账号或密码错误');
        }      
      
        if (md5($param['params']['password']) != $user['password']) {
            error('密码错误');
        }
        if ($user['status'] == 0) {
            error('账号已被禁用，请联系管理员');
        }
        if ($user['is_delete'] == 0) {
            error('账号已被删除，请联系管理员');
        }
        $user_id = $user[$pk];
        $group_id = Db::name('auth_group_access')->field('group_id')->where('uid',$user_id)->find();   

        $ip_info = Utils::ipInfo();
        $user_log['user_id']     = $user[$pk];
        $user_log['login_ip']     = $ip_info['ip'];
        // $user_log['login_region'] = $ip_info['region'];m
        $user_log['log_time']   = date('Y-m-d H:i:s');
        $user_log['response_msg']  = '登录成功';  
        
        UserLogService::add($user_log, SettingService::LOG_TYPE_LOGIN); 
        $data=['user'=>$user,'group_id'=>$group_id];
    
        return $data;
    }
    
      /**
     * 用户信息删除   
     * @return array|Exception
     */
    public static function delete($param)
    {           
        $UserModel = new UserModel(); 
        $pk = $UserModel->getPk();  
        $params= $param['params'];
        $where[] = [$pk, '=', $params['id']];
       
        if ($UserModel->where('status',1)->where($where)->find()) {
            error('删除用户需要先禁用后才可以删除');
        }
        $data['is_delete']=0;
        $user = $UserModel->where($where)->update($data);   
        if ($user) {
            return true;
        } else {
            error('删除失败');
        }     
    }

     /**
     * 用户修改回显   
     * @return array|Exception
     */
    public static function  purview($param){
        $model = new UserModel(); 
        $pk = $model->getPk();  
        $params= $param['params'];
        $where[] = [$pk, '=', $params['id']];
        $field =  $pk. ',username,nickname,email,phone,status,storgeid';
        $info = $model->where($where)->field($field)->find();       
        $info['groups']=Db::name('auth_group_access')->where('uid',$info['id'])->column('group_id');
        return $info;
    }
     /**
     * 修改账户跟权限分组的设置   
     * @return array|Exception
     */
    public static function  create_purview($param){
        $model = new UserModel(); 
        $pk = $model->getPk();  
        $params= $param['params'];
      
        $data=[ 
            'username' => $params['username'],
            'nickname' => $params['nickname'],
            'phone' => $params['phone'],         
            'email' => $params['email'],
            'status' => $params['status'],     
            'password' => $params['password'],   
            'storgeid'   => $params['storgeid'],   
        ];
        
        //判断修改是否有密码是否有密码
        if($params['password']=="******"){
            unset($data['password']);
        }
    //    开始事务 
       DB::startTrans();
       try{
            //修改用户信息           
            if(isset($params[$pk])){              
                //有值则说明是修改     
               $model::find($params[$pk])->save($data); 
                $id=$params[$pk]; 
            }else{              
                $data['registertime']=datetime();
                $data['registerYmd']=(int)date('Ymd',time());
                //执行添加数据                           
                $id= $model->insertGetId($data); 
            }
            
            //修改用户的权限分组
            if($params['groups']){
                //先删除权限分组 
                Db::name('auth_group_access')->where('uid',$id)->delete(); 
                //再插入权限分组
                $datagroup=[];         
                foreach ($params['groups'] as  $v) {
                    $data_group['uid'] = $id;
                    $data_group['group_id'] = $v; 
                    $datagroup[]=$data_group;
                }
              Db::name('auth_group_access')->insertAll($datagroup);
               
            } 
           
            Db::commit();
            return true;
        }  catch(\Exception $e){
            Db::rollback();
            error('修改失败');
         }       

    } 

      /**
     * 用户退出
     *
     * @param int $id 用户id
     * 
     * @return array
     */
    public static function logout($user)
    { 
        
        session('user',null);     
    
    }

     /**
     * 用户修改密码
     *
     * @param int $param  修改密码的信息
     * 
     * @return array
     */

     public static function  changpass($param){
        //先判断token是否正确
        $token = $param['params']['token'];
        //获取缓存
        $user_data = session('user');    
        //查询数据是否存在   
        $model = new UserModel();
        $user =   $model::find($user_data['id'], md5($param['params']['old_password']));      
        
        if (empty($user->toArray())) {
            error('没有查到用户，请核实输入旧密码是否正确');
        } 
        if($user->toArray()['status']!=1){
            error('用户已被禁用，请联系管理员');
        }
         //执行修改密码
         $user->password =  md5($param['params']['new_password']);     ;       
         $reslut = $user->save(); 
         return $reslut;        
     }

         /**
     * 获取权限组下面用户
     *
     * @param int $param  修改密码的信息
     * 
     * @return array
     */

     public static function get_group_user_list($param){
        $params= $param['params'];
        $UserModel = new  UserModel();
        $data = $UserModel->getuserlist( $params['group_id']);  
        $reslut['list']=$data;
        return $reslut;       
     }

}